package com.fsquare.dao.social;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.broadleafcommerce.common.persistence.EntityConfiguration;
import org.springframework.stereotype.Repository;

import com.fsquare.domain.social.SocialToken;

@Repository("socialTokenDao")
public class SocialTokenDaoImpl implements SocialTokenDao{

	@PersistenceContext(unitName = "blPU")
    protected EntityManager em;

    @Resource(name = "blEntityConfiguration")
    protected EntityConfiguration entityConfiguration;
    
    public SocialToken getSocialTokenById(final Long id) {
    	try{
    		return em.find(SocialToken.class, id);
	    }catch(NoResultException ex){}
		return null;
    }
	
	
	@Override
	public SocialToken getSocialTokenByKey(String key) {
		try{
			final Query query = em.createNamedQuery("SOCIAL_TOKEN_BY_KEY");
	        query.setParameter("key", key);
	        return (SocialToken)query.getSingleResult();
		}catch(NoResultException ex){}
		return null;
	}

	@Override
	public SocialToken saveSocialToken(SocialToken socialToken) {
		
//		SocialToken response = null;

    	if(socialToken.getId() == null)
    		em.persist(socialToken);
        else
        	em.merge(socialToken);
		
		return socialToken;
	}

	@Override
	public SocialToken createSocialToken() {
		SocialToken socialToken = (SocialToken) entityConfiguration.createEntityInstance(SocialToken.class.getName());
        return socialToken;
	}


	@Override
	public SocialToken getSocialTokenByKeyAndProvider(String key, String provider) {
		try{
			final Query query = em.createNamedQuery("SOCIAL_TOKEN_BY_KEY_AND_PROVIDER");
	        query.setParameter("key", key);
	        query.setParameter("provider", provider);
	        return (SocialToken)query.getSingleResult();
		}catch(NoResultException ex){}
		return null;
	}


	@Override
	public SocialToken getSocialTokenByProviderAndUsername(String provider, String username) {
		try{
			final Query query = em.createNamedQuery("SOCIAL_TOKEN_BY_PROVIDER_AND_USERNAME");
	        query.setParameter("provider", provider);
	        query.setParameter("username", username);
	        return (SocialToken)query.getSingleResult();
		}catch(NoResultException ex){}
		return null;
	}
}
